package com.rqf.ls.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.rqf.ls.service.ICommonDataService;
import com.rqf.ls.service.IRegisterService;
import com.server.password.MyMD5;
import com.server.web.DataVector;
import com.server.web.RequestInput;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.AlibabaAliqinFcSmsNumSendRequest;
import com.taobao.api.response.AlibabaAliqinFcSmsNumSendResponse;

@Service("RegisterService")
public class RegisterService implements IRegisterService {
	
	@Autowired
	private JdbcTemplate jdbcTemplate;
	@Autowired
	private ICommonDataService commonDataService;
	
	/**
	 * 向手机发送验证码
	 * @param phoneNo
	 * @return
	 * @author ServerZhang
	 * @date 2016年3月16日
	 */
	@Override
	public String sendCode(String phoneNo){
		StringBuffer codeBuffer = new StringBuffer();
		List<Integer> tempList = new ArrayList<Integer>();
		for (int i = 0; i < 10; i++) {
			tempList.add(i);
		}
		int tempInt = 0;
		while (tempInt < 6) {
			int index = (int)(Math.random() * 9);
			Integer integer = tempList.get(index);
			if (integer.equals(-1)) {
				continue;
			}
			codeBuffer.append(integer);
			integer = -1;
			tempList.set(index, integer);
			tempInt ++;
		}
		//TODO 调用第三方服务发送手机验证码
		String url = "http://gw.api.taobao.com/router/rest";
		String appkey = "23363567";
		String secret = "77de197e7455a3cfc50deb3e7e3a5ee8";
		TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
		AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
		req.setExtend("123456");
		req.setSmsType("normal");
		req.setSmsFreeSignName("注册验证");
		req.setSmsParamString("{\"code\":\""+codeBuffer.toString()+"\",\"product\":\"艾特律师\"}");
		req.setRecNum(phoneNo);
		req.setSmsTemplateCode("SMS_7300743");
		AlibabaAliqinFcSmsNumSendResponse rsp;
		try {
			rsp = client.execute(req);
		} catch (ApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//System.out.println(rsp.getBody());
		
		/*String url = "http://101.200.130.93:9001/sms.aspx";//
		String userid = "152";//企业id
		String account = "594962949";//发送用户帐号
		String password = "v5u5w4h3b1";//发送帐号密码
		String mobile = "13408102374";//全部被叫号码
		String content = "欢迎注册瑞七方律师助手，手机验证码为：569426，有效时间10分钟，请妥善保管验证码。";//发送内容
		SmsClientSend.sendSms(url, userid, account, password, mobile, content);*/
		
		return codeBuffer.toString();
	}
	
	 /**
	 * 检查用户是否已注册
	 * @return
	 * @author ServerZhang
	 * @date 2016年3月16日
	 */
	@Override
	public Boolean checkPhone(String phoneNo){
		String sql = "Select count(Id) from normaluser where Phone='"+phoneNo+"'";
		int count = jdbcTemplate.queryForInt(sql);
		if (count > 0) {
			return false;
		}else {
			return true;
		}
	}
	@Override
	public Boolean checkNickName(String phoneNo, String nickName){
		String sql = "Select count(Id) from normaluser where nickname='"
				+nickName+"' and phone!='"
				+phoneNo+"'";
		int count = jdbcTemplate.queryForInt(sql);
		if (count > 0) {
			return false;
		}else {
			return true;
		}
	}
	@Override
	public Boolean checkUserName(String phoneNo, String userName){
		String sql = "Select count(Id) from normaluser where username='"
				+userName+"' and phone!='"
				+phoneNo+"'";
		int count = jdbcTemplate.queryForInt(sql);
		if (count > 0) {
			return false;
		}else {
			return true;
		}
	}
	@Override
	public Boolean checkUser(String phoneNo, String name){
		String sql = "Select count(Id) from normaluser where (username='"
				+name+"' or nickname='"
				+name+"' or phone='"
				+name+"') and phone!='"
				+name+"'";
		int count = jdbcTemplate.queryForInt(sql);
		if (count > 0) {
			return false;
		}else {
			return true;
		}
	}
	
	 /**
	 * 增加用户
	 * @return
	 * @author ServerZhang
	 * @date 2016年3月16日
	 */
	@Override
	public Boolean add(Map<String, Object> userMap){
		Boolean isSuccess = true;
		Object phoneObj = userMap.get("phoneNo");
		Object pswObj = userMap.get("password");
		if (phoneObj == null || pswObj == null) {
			isSuccess = false;
			return isSuccess;
		}
		//MD5经过3次加密
		String encryptStr = MyMD5.circularlyEncrypt(pswObj.toString(), 3);
		
		// 添加用户
		String sql = "insert into normaluser (id,REGISTTIME,phone,nickname,userPwd,PHONECHECKED,ABLE) values(normaluser_sequence.nextval,SYSDATE,'"
				+phoneObj+"','"+phoneObj+"','"+encryptStr+"',1,1)";
		try {
			jdbcTemplate.execute(sql);
		} catch (Exception e) {
			isSuccess = false;
		}
		return isSuccess;
	}
	
	 /**
	 * 个人资料编辑
	 * @param phoneNo
	 * @param userMap
	 * @return
	 * @author ServerZhang
	 * @date 2016年3月17日
	 */
	@Override
	public Boolean update(String phoneNo,Map<String, Object> userMap){
		Boolean isSuccess = true;
		Set<String> keySet = userMap.keySet();
		int index = 0;
		StringBuffer sqlBuffer = new StringBuffer();
		sqlBuffer.append("Update normaluser set ");
		for(String key : keySet){
			if (index != 0) {
				sqlBuffer.append(",");
			}
			sqlBuffer.append(key).append("='").append(userMap.get(key)).append("'");
			index ++;
		}
		sqlBuffer.append(" where phone='").append(phoneNo).append("'");
		try {
			jdbcTemplate.execute(sqlBuffer.toString());
		} catch (Exception e) {
			isSuccess = false;
		}
		return isSuccess;
	}
	@Override
	public Boolean update(String phoneNo,String field,String value){
		Boolean isSuccess = true;
		String sql = "Update normaluser set "+field+"='"+value+"'";
		try {
			jdbcTemplate.execute(sql);
		} catch (Exception e) {
			isSuccess = false;
		}
		return isSuccess;
		
	}
	 /**
	 * 获取用户信息
	 * @param phoneNo
	 * @param field
	 * @return
	 * @author ServerZhang
	 * @date 2016年3月17日
	 */
	@Override
	public Map<String, Object> read(String phoneNo){
		String sql = "Select * from normaluser where phone='"
				+phoneNo+"' and able=1";
		List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
		if (list.size() > 0) {
			return list.get(0);
		}else {
			return new HashMap<String, Object>();
		}
	}
	@Override
	public Object read(String phoneNo, String field){
		String sql = "Select " + field +" from normaluser where phone='"
				+phoneNo+"' and isAble=1";
		List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
		if (list.size() > 0) {
			return list.get(0).get(field);
		}else {
			return null;
		}
	}
	 /**
	 * 修改密码
	 * @param phoneNo
	 * @param password
	 * @return
	 * @author ServerZhang
	 * @date 2016年3月18日
	 */
	@Override
	public Boolean updatePswd(String phoneNo,String password){
		String encrypt = MyMD5.circularlyEncrypt(password, 3);
		return this.update(phoneNo, "userPwd", encrypt);
	}
	/**
	 * 获取用户头像路径
	 * @param phoneNo
	 * @return
	 * @author ServerZhang
	 * @date 2016年5月10日
	 */
	@Override
	public String getPhotoPath(String phoneNo) {
		String path = "";
		String sql = "Select * from ATTACHMENT where saveType='Photo' and isable=1 %s order by createTime desc";
		List<Map<String, Object>> list = jdbcTemplate.queryForList(String
				.format(sql, "and phoneNo='" + phoneNo +"'"));
		if (list.size() > 0) {
			Map<String, Object> map = list.get(0);
			Object pathObj = map.get("FILEPATH");
			Object uuidObj = map.get("UUID");
			Object typeObj = map.get("TYPE");
			if (pathObj != null && uuidObj != null && typeObj != null) {
				path += pathObj.toString() +"\\" + uuidObj.toString()
						+"."+ typeObj.toString();
			}
		}
		return path;
	}
	 /**
	 * 所有用户列表
	 * @param requestInput
	 * @param type 0、正常用户；1、黑名单用户；其他为所有用户
	 * @return
	 * @author ServerZhang
	 * @date 2016年5月13日
	 */
	@Override
	public DataVector<Map<String, Object>> userList(RequestInput requestInput,Integer inBlackList){
		String table = "NORMALUSER";
		String _whereStr = null;
		String sortStr = "";
		if (inBlackList != null) {
			switch (inBlackList) {
			case 0:
				_whereStr = "INBLACKLIST=0";
				break;
			case 1:
				_whereStr = "INBLACKLIST=1";
				break;

			default:
				break;
			}
		}
		DataVector<Map<String, Object>> listData = commonDataService.getListData(table, _whereStr, sortStr, requestInput);
		return listData;
	}
	 
	/**
	 * 拉黑、解除拉黑
	 * 
	 * @param phoneNo
	 * @param inBlackList
	 * @return
	 * @author ServerZhang
	 * @date 2016年5月17日
	 */
	@Override
	public Boolean pullToBlack(String phoneNos, Integer inBlackList) {
		String phoneStrs = "'"+phoneNos.replace(",", "','")+"'";
		Boolean isSuccess = true;
		String sql = "Update NORMALUSER set INBLACKLIST=" + inBlackList
				+ " where phone in(" + phoneStrs + ")";
		try {
			jdbcTemplate.execute(sql);
		} catch (Exception e) {
			isSuccess = false;
		}
		return isSuccess;
	}
	
	
}
